﻿using Architecture.Domain.Service;
using Architeture.Domain;
using Architeture.Domain.DTO;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using RBAC.ZhuBoLin.Application.Command.RoleCommand;
using RBAC.ZhuBoLin.Dtos;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using static Architecture.Domain.Service.UserService;

namespace RBAC.ZhuBoLin.Controllers
{
    /// <summary>
    /// 用户
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class UserController : ControllerBase
    {
        private readonly IConfiguration configuration;
        protected readonly IUserService userservice;
        protected readonly IMediator mediator;

        public UserController(IConfiguration configuration, IUserService userservice, IMediator mediator)
        {
            this.configuration = configuration;
            this.userservice = userservice;
            this.mediator = mediator;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public async Task<ApiResult<string>> UserLogin(string name, string pwd)
        {
            ApiResult<string> result = new ApiResult<string>();
            try
            {
                var arr = await userservice.UserLogin(name, pwd);
                if (arr.code == 1)
                {
                    //返回token
                    result.Data = jwtNewString((await userservice.UserLogin(name, pwd)).id.ToString(), arr.rid);
                }
                if (arr.code == 2)
                {
                    result.Code = 2;
                    result.Message = "密码错误";
                }
                if (arr.code == 3)
                {
                    result.Code = 3;
                    result.Message = "用户名不存在";
                }

            }
            catch (Exception ee)
            {
                result.Code = -1;
                result.Message = ee.Message;
                throw;
            }
            return result;

        }
        /// <summary>
        /// 签发token令牌
        /// </summary>
        /// <param name="uid">用户唯一标识</param>
        /// <returns></returns>
        private string jwtNewString(string uid, string rid)
        {
            //生成jwt
            //Header  选择签名算法
            var signingAlogorithm = SecurityAlgorithms.HmacSha256;
            //Payload   存放用户信息，下面我们放了一个用户id
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub,uid),
                new Claim(ClaimTypes.Role, rid),
                //new Claim(ClaimTypes.UserData, "测试")
            };
            //Signature
            //取出私钥并以utf8编码字节输出
            var secreByte = Encoding.UTF8.GetBytes(configuration["Authentication:SecretKey"]);
            //使用非对称算法对秘钥进行加密
            var signinKey = new SymmetricSecurityKey(secreByte);
            //使用HmacSha256来验证加密后的私钥生成数字签名
            var signingCredentials = new SigningCredentials(signinKey, signingAlogorithm);
            //生成token
            var Token = new JwtSecurityToken(
                issuer: configuration["Authentication:Issuer"],  //发布者
                audience: configuration["Authentication:Audience"],  //接受者
                claims: claims,  //存放用户信息
                notBefore: DateTime.UtcNow,  //发布时间
                expires: DateTime.UtcNow.AddDays(1),  //有效期设置为一天
                signingCredentials //数字签名
                );
            //生层字符串token
            var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token);
            return TokenStr;
        }
        /// <summary>
        /// 反填用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<SetUserInfo>>> GetUserJwt()
        {
            ApiResult<List<SetUserInfo>> result = new ApiResult<List<SetUserInfo>>();
            try
            {
                var ids = Convert.ToInt32(HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
                result.Data = await userservice.GetUserJwt(ids);
            }
            catch (Exception ee)
            {
                result.Code = 1;
                result.Message = ee.Message;
                throw;
            }
            return result;

        }
        /// <summary>
        /// 返回菜单用户名和菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 
        [HttpGet]
        public async Task<ApiResult<List<MenuSetDto>>> GetUserMenuJwt()
        {


            ApiResult<List<MenuSetDto>> result = new ApiResult<List<MenuSetDto>>();
            try
            {
                var id = Convert.ToInt32(HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
                result.Data = await userservice.GetUserMenuJwt(id);
            }
            catch (Exception ee)
            {
                result.Code = 1;
                result.Message = ee.Message;
                throw;
            }
            return result;
        }


        [HttpPost]
        public async Task<ApiResult<int>> UserRoleAddNew(UserRoleNewCreateCommand md)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                result.Data = await mediator.Send(md);
            }
            catch (Exception ee)
            {
                result.Code = 1;
                result.Message = ee.Message;
                throw;
            }
            return result;
        }


        /// <summary>
        /// 用户添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<int>> AddUser(UserCreateCommand ud)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                result.Data = await mediator.Send(ud);
            }
            catch (Exception ee)
            {
                result.Code = 1;
                result.Message = ee.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 返回用户详情显示
        /// </summary>
        /// <returns></returns>

        [HttpGet]
        public async Task<ApiResult<UserPage>> GetUserInfo([FromQuery] UserSelectCommand sd)
        {
            ApiResult<UserPage> result = new ApiResult<UserPage>();
            try
            {
                result.Data = await mediator.Send(sd);
            }
            catch (Exception ex)
            {
                result.Code = 1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 用户删除
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        /// 
        [HttpPut]
        public async Task<ApiResult<int>> UserDel([FromQuery] UserDeleteCommand dd)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                result.Data = await mediator.Send(dd);
            }
            catch (Exception ex)
            {
                result.Code = 1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }

        /// <summary>
        /// 返回用户详情赋值
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<UserInfo>> SetUserInfo([FromQuery] UserSetCommand sd)
        {
            ApiResult<UserInfo> result = new ApiResult<UserInfo>();
            try
            {
                result.Data = await mediator.Send(sd);
            }
            catch (Exception ex)
            {
                result.Code = 1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 用户信息修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// 
        [HttpPut]
        public async Task<ApiResult<int>> UserUp(UserUpdateCommand ud)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                result.Data = await mediator.Send(ud);
            }
            catch (Exception ex)
            {
                result.Code = 1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 返回用户部门树形
        /// </summary>
        /// <param name="bid"></param>
        /// <returns></returns>

        [HttpGet]
        public async Task<ApiResult<List<mentumn>>> GetUserTree([FromQuery] UserGetTreeCommand td)
        {
            ApiResult<List<mentumn>> result = new ApiResult<List<mentumn>>();
            try
            {
                result.Data = await mediator.Send(td);
            }
            catch (Exception ex)
            {
                result.Code = 1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }

        [HttpPost]
        public async Task<ApiResult<int>> UserRoleAdd(UserRoleCreateCommand rcd)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                result.Data = await mediator.Send(rcd);
            }
            catch (Exception ex)
            {
                result.Code = 1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }


        [HttpGet]
        public async Task<ApiResult<List<UserRoleChed>>> GetUserRoleched([FromQuery] UserSetRoleCommand srd)
        {
            ApiResult<List<UserRoleChed>> result = new ApiResult<List<UserRoleChed>>();
            try
            {
                result.Data = await mediator.Send(srd);
            }
            catch (Exception ex)
            {
                result.Code = 1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        [HttpGet]
        public async Task<ApiResult<List<ByUserInfo>>> GetUerInfoBybid([FromQuery] UserGetInfoCommand gd)
        {
            ApiResult<List<ByUserInfo>> result = new ApiResult<List<ByUserInfo>>();
            try
            {
                result.Data = await mediator.Send(gd);
            }
            catch (Exception ex)
            {
                result.Code = 1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
        /// <summary>
        /// 用户角色删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpPut]
        public async Task<ApiResult<int>> UserRoleDel(UserRoleDeleteCommand id)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                result.Data = await mediator.Send(id);
            }
            catch (Exception ex)
            {
                result.Code = 1;
                result.Message = ex.Message;
                throw;
            }
            return result;
        }
    }
}
